using PKGames.SceneManagement;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

namespace PKGames.AssetBundleSystem
{
	public class SceneManagerHelper : MonoSingleton<SceneManagerHelper>
	{
		private Dictionary<string, List<string>> _sceneEmbeddedDependencies = new Dictionary<string, List<string>>
		{
			{
				"VoxelPlayerWorldSelector",
				new List<string>
				{
					"voxelplayerworldembedded_v1"
				}
			}
		};

		protected override void Awake()
		{
			base.Awake();
			MonoSingleton<SceneLoader>.Instance.OnPKGamesContextFinished = Cleanup;
		}

		private IEnumerator LoadEmbeddedAssetBundleDependencies(string sceneName, bool additive = false)
		{
			List<string> dependencies = GetEmbeddedDependencies(sceneName);
			UnityEngine.Debug.Log("Dependencies count: " + dependencies.Count);
			if (dependencies.Count > 0)
			{
				foreach (string dependency in dependencies)
				{
					yield return LoadLocalAssetBundle(dependency, isEmbedded: true);
				}
				SetupUnload();
			}
			else
			{
				UnityEngine.Debug.Log(base.Tag + " No Asset Bundles available for " + sceneName);
			}
			yield return MonoSingleton<SceneLoader>.Instance.LoadSubSceneAsync(sceneName, storeInSceneHistory: true, additive);
		}

		private List<string> GetEmbeddedDependencies(string sceneName)
		{
			if (_sceneEmbeddedDependencies.ContainsKey(sceneName))
			{
				return _sceneEmbeddedDependencies[sceneName];
			}
			return new List<string>();
		}

		public IEnumerator LoadAssetBundleDependencies(string sceneName, bool isAdditive = false)
		{
			yield return LoadEmbeddedAssetBundleDependencies(sceneName, isAdditive);
		}

		private IEnumerator LoadLocalAssetBundle(string assetBundleName, bool isEmbedded)
		{
			yield return StartCoroutine(MonoSingleton<AssetBundleManager>.Instance.LoadLocalAssetBundle(assetBundleName, isEmbedded, null, null));
		}

		private void SetupUnload()
		{
			UnityAction<Scene> onSceneUnloaded = null;
			onSceneUnloaded = delegate
			{
				UnityEngine.Resources.UnloadUnusedAssets();
				GC.Collect();
				SceneManager.sceneUnloaded -= onSceneUnloaded;
			};
			SceneManager.sceneUnloaded += onSceneUnloaded;
		}

		private void Cleanup()
		{
			MonoSingleton<AssetBundleManager>.Instance.UnloadAllAssetBundles();
			UnityEngine.Resources.UnloadUnusedAssets();
			GC.Collect();
		}
	}
}
